package com.xiaoluo.a08_foreground;

import android.app.ActivityManager;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.util.List;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        KeepAliveHelperService.keep(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // isRun(this, "");
        //getActivityManager();
        //isAppForeground(this);
        ForegroundAppUtil.getForegroundActivityName(this);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // no
    private void getActivityManager() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runnings = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : runnings) {
            if (info.baseActivity != null) {
                Log.i("xl", info.baseActivity.getPackageName());
            }
        }
    }

    //sharedusedid的话可以准确的判断是否前台进程
    public static boolean isAppForeground(Context context) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Service.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList =
                null;
        if (activityManager != null) {
            runningAppProcessInfoList = activityManager.getRunningAppProcesses();
        }
        if (runningAppProcessInfoList == null) {
            Log.i("SilentUpgradeDownloadIn", "runningAppProcessInfoList is null!");
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {
            Log.i("SilentUpgradeDownloadIn", "packageName :" + processInfo.processName);
            if ((processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
                Log.i("SilentUpgradeDownloadIn", "pkgName :" + processInfo.processName);
                return true;
            } else {
                Log.i("SilentUpgradeDownloadIn", "not foreground pkgName :" + processInfo.processName);
            }

        }
        return false;
    }

    //
    public boolean isAppOnForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        boolean isOnForground = false;
        List<ActivityManager.RunningAppProcessInfo> runnings = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo running : runnings) {
            Log.i("SilentUpgradeDownloadIn", "packageName :" + running.processName);
            if (running.processName.equals(getPackageName())) {
                if (running.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        || running.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
                    //前台显示...
                    Log.e("my", "前台显示");
                    isOnForground = true;
                } else {
                    //后台显示...
                    Log.e("my", "后台显示");
                    isOnForground = false;
                }
                break;
            }
        }
        String currentPackageName = "";
        if (am.getRunningTasks(1).size() > 0) {
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            currentPackageName = cn.getPackageName();
        }
        Log.i("SilentUpgradeDownloadIn", "isAppOnForeground  :" + currentPackageName);
//        return !TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(getPackageName());
        return isOnForground;
    }


    public void isForegroundPkgName(Context context) {
        UsageStatsManager m = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        String topActivity = "";

        if (m != null) {
            long now = System.currentTimeMillis();
            List<UsageStats> stats = m.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, now);
            //取得最近运行的一个app，即当前运行的app
            if ((stats != null) && (!stats.isEmpty())) {
                int j = 0;
                for (int i = 0; i < stats.size(); i++) {
                    if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
                        j = i;
                    }
                    if (!stats.get(j).getPackageName().equals("com.swaiotos.appstore")) {
                        topActivity = stats.get(j).getPackageName();
                    }
                }
                Log.i("SilentUpgradeDownloadIn", "in the end running app is : " + topActivity);
            }
        }
        Log.i("SilentUpgradeDownloadIn", "******currentTopApkName :" + topActivity);
    }

    /*
判断service是否运行
*/
    public static boolean isRun(Context context, String serviceName) {
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runServiceList = mActivityManager.getRunningServices(100);
        Log.i("SilentUpgradeDownloadIn", "running service  size: " + runServiceList.size());
        for (ActivityManager.RunningServiceInfo info : runServiceList) {
            if (info.foreground) {
                String name = info.service.getPackageName();
                Log.i("SilentUpgradeDownloadIn", "running service : " + name);
            }
        }
        return false;
    }
}
